﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Windows.ApplicationModel.DataTransfer;
using Windows.Data.Xml.Dom;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Navigation;
using Catalogo.Portable.Model;
using Catalogo.Windows8.Common;
using Catalogo.Portable.ViewModel;
using Catalogo.Portable.ViewModel.Messages;

namespace Catalogo.Windows8.Views
{
    public sealed partial class ItemPage : LayoutAwarePage
    {
        private DataTransferManager dataTransferManager;
        private DataPackage requestData;
        private static Uri _baseUri = new Uri("ms-appx:///");

        public ItemPageViewModel ViewModel
        {
            get
            {
                if (this.DefaultViewModel.ContainsKey("ViewModel"))
                {
                    return this.DefaultViewModel["ViewModel"] as ItemPageViewModel;
                }
                return null;
            }
            set { this.DefaultViewModel["ViewModel"] = value; }
        }

        public ItemPage()
        {
            this.InitializeComponent();
        }

        protected override async void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            if (ViewModel == null)
            {
                ViewModel = new ItemPageViewModel();
                ViewModel.Messenger.Subscribe<NavegarParaPagina>(NavegarParaPaginaMessageHandler.NavegarParaPagina);
                await ViewModel.LoadAsync((string)navigationParameter);
            }
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            this.dataTransferManager = DataTransferManager.GetForCurrentView();
            this.dataTransferManager.DataRequested += OnDataRequested;
            this.dataTransferManager.TargetApplicationChosen += dataTransferManager_TargetApplicationChosen;
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);

            ViewModel.Messenger.Unsubscribe<NavegarParaPagina>(NavegarParaPaginaMessageHandler.NavegarParaPagina);

            this.dataTransferManager.DataRequested -= OnDataRequested;
            this.dataTransferManager.TargetApplicationChosen -= dataTransferManager_TargetApplicationChosen;
        }

        private async void OnDataRequested(DataTransferManager sender, DataRequestedEventArgs e)
        {
            if (ViewModel.Item != null)
            {
                requestData = e.Request.Data;
                requestData.Properties.Title = ViewModel.ObterTituloParaCompartilhar();
                requestData.Properties.Description = ViewModel.Item.Descricao;
                requestData.SetText(ViewModel.Item.Descricao);

                var imageStreamRef = RandomAccessStreamReference.CreateFromUri(new Uri(_baseUri, ViewModel.Item.ImageUrl));
                if (imageStreamRef != null)
                {
                    requestData.Properties.Thumbnail = imageStreamRef;
                    requestData.SetBitmap(imageStreamRef);
                }

                var htmlParaCompartilhar = await ViewModel.ObterHtmlParaCompartilharAsync();
                requestData.SetHtmlFormat(HtmlFormatHelper.CreateHtmlFormat(htmlParaCompartilhar));
            }
            else
            {
                e.Request.FailWithDisplayText("Selecione o item que deseja compartilhar e tente novamente.");
            }
        }

        async void dataTransferManager_TargetApplicationChosen(DataTransferManager sender, TargetApplicationChosenEventArgs args)
        {
            try
            {
                if (!(args.ApplicationName == "Email" || args.ApplicationName == "Mail"))
                {
                    requestData.SetUri(ViewModel.ObterUriParaCompartilhar());
                }
            }
            catch { }
        }
    }
}
